Creating a Dictionary¶
1. Literal syntax - {key: value,}¶
Key must be a hashable immutable type.
D = {
'one': 'uno',
2: 'dos',
'three': 'tres',
}
Output:
{'one': 'uno', 2: 'dos', 'three': 'tres'}
2. Use dict() value constructor and a pass keyword arguments¶
Key must be a string.
D = dict(
one = 'uno',
two = 'dos',
)
Output:
::
{'one': 'uno', 'two': 'dos'}
3. Pass a collection (list) of a key-value pairs (tuples)¶
D = dict(
[
('one', 'uno'),
('two', 'dos'),
('three', 'tres'),
]
)
Output:
{'one': 'uno', 'two': 'dos', 'three': 'tres'}
4. Use dict.fromkeys() method¶
Use collection as a dict keys [used before we had a “set” type]
Useful to count each letter in a word
from string import ascii_lowercase
D = dict.fromkeys(ascii_lowercase)
# D = dict.fromkeys(ascii_lowercase, 0) # with default value
Output:
{'a': None,
'b': None,
'c': None,
. . .
'x': None,
'y': None,
'z': None}
5. Use a dict value constructor and pass it to an existing dictionary¶
Creates a shallow copy of the existing dict - keys are the same but values could be different.
D = {1:1, 2:4, 3:9}
D1 = dict(D)
D1[2], D2[3] = 8, 27
D, D1
Output:
({1: 1, 2: 4, 3: 9}, {1: 1, 2: 8, 3: 27})